# -*- coding: utf-8 -*-
# @Time    : 2024/5/9 10:35
# @Author  : Jonny
# @File    : LuckEwHelperUtils.py
# @Describe: 企业微信逻辑服务层

import base64
import requests
import json
from luck.core.LuckConstant import LuckConstant

class LuckEwHelperUtils(object):

    def __init__(self, config):
        self.config = config

    CONTENT_TYPE = 'application/json'

    def __is_phone_number(self, s):
        """判断字符串s是否是手机号码"""
        if isinstance(s, str) and len(s) == 11 and s.startswith('1'):
            try:
                # 尝试将字符串转换为整数（只包含数字的字符串可以转换）
                int(s)
                return True
            except ValueError:
                # 如果包含非数字字符，则不是手机号码
                return False
        return False

        # 发送群机器人文本消息
    def send_text_msg_to_group(self, dingtalk_content, dingtalk_userid):
        try:

            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "发送群机器人文本消息 失败"
            }
        except Exception as e:
            raise e

    # 发送个人文本消息
    def send_text_msg_to_user(self, ew_content, ew_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            ew_app_key = self.config["ew_app_key"]
            ew_app_secret = self.config["ew_app_secret"]
            ew_url = self.config["ew_url"]
            ew_url_basic_auth1 = self.config["ew_url_basic_auth1"]
            ew_url_basic_auth2 = self.config["ew_url_basic_auth2"]

            auth = str(base64.b64encode(f'{ew_url_basic_auth1}:{ew_url_basic_auth2}'.encode('utf-8')),
                       'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{ew_url}/sendTextMsgToPerson"

            if ew_userid is not None and len(ew_userid) > 0:
                ew_userid_list = []
                ew_usermobile_list = []
                for ele in ew_userid.split(","):
                    if self.__is_phone_number(ele):
                        ew_usermobile_list.append(ele)
                    else:
                        ew_userid_list.append(ele)

                if len(ew_userid_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_userid_list": ew_userid_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if len(ew_usermobile_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_usermobile_list": ew_usermobile_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if res.status_code == 200:
                    return result
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "发送个人文本消息 失败"
            }
        except Exception as e:
            raise e

    # 发送个人文本卡片消息
    def send_textcard_msg_to_user(self, ew_content, ew_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            ew_app_key = self.config["ew_app_key"]
            ew_app_secret = self.config["ew_app_secret"]
            ew_url = self.config["ew_url"]
            ew_url_basic_auth1 = self.config["ew_url_basic_auth1"]
            ew_url_basic_auth2 = self.config["ew_url_basic_auth2"]

            auth = str(base64.b64encode(f'{ew_url_basic_auth1}:{ew_url_basic_auth2}'.encode('utf-8')),
                       'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{ew_url}/sendMarkdownMsgToPerson"

            if ew_userid is not None and len(ew_userid) > 0:
                ew_userid_list = []
                ew_usermobile_list = []
                for ele in ew_userid.split(","):
                    if self.__is_phone_number(ele):
                        ew_usermobile_list.append(ele)
                    else:
                        ew_userid_list.append(ele)

                if len(ew_userid_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_userid_list": ew_userid_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if len(ew_usermobile_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_usermobile_list": ew_usermobile_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if res.status_code == 200:
                    return result
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "发送个人文本卡片消息 失败"
            }
        except Exception as e:
            raise e

    # 发送个人Markdown消息
    def send_markdown_msg_to_user(self, ew_content, ew_userid):
        try:
            agent_id = self.config["agent_id"]
            app_key = self.config["app_key"]
            app_secret = self.config["app_secret"]

            ew_app_key = self.config["ew_app_key"]
            ew_app_secret = self.config["ew_app_secret"]
            ew_url = self.config["ew_url"]
            ew_url_basic_auth1 = self.config["ew_url_basic_auth1"]
            ew_url_basic_auth2 = self.config["ew_url_basic_auth2"]

            auth = str(base64.b64encode(f'{ew_url_basic_auth1}:{ew_url_basic_auth2}'.encode('utf-8')),
                       'utf-8')
            headers = {
                'Content-Type': self.CONTENT_TYPE,
                'Authorization': f'Basic {auth}'
            }
            url = f"{ew_url}/sendMarkdownMsgToPerson"

            if ew_userid is not None and len(ew_userid) > 0:
                ew_userid_list = []
                ew_usermobile_list = []
                for ele in ew_userid.split(","):
                    if self.__is_phone_number(ele):
                        ew_usermobile_list.append(ele)
                    else:
                        ew_userid_list.append(ele)

                if len(ew_userid_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_userid_list": ew_userid_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if len(ew_usermobile_list) > 0:
                    msg = {
                        "agent_id": agent_id,
                        "app_key": app_key,
                        "app_secret": app_secret,

                        "ew_app_key": ew_app_key,
                        "ew_app_secret": ew_app_secret,

                        "ew_type": "touser",
                        "ew_content": ew_content,
                        "ew_usermobile_list": ew_usermobile_list
                    }
                    res = requests.post(url, data=json.dumps(msg), headers=headers)
                    result = res.json()

                if res.status_code == 200:
                    return result
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "发送个人Markdown消息 失败"
            }
        except Exception as e:
            raise e